<template>
<div>
  <div class="crumbs">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>
        <i class="el-icon-odometer"></i> 机器学习流水线
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div class="container">
    <el-table
        :data="tableData" border class="table" ref="multipleTable"
        header-cell-class-name="table-header"
    >
      <el-table-column prop="pipelineName" label="流水线名"></el-table-column>
      <el-table-column prop="features" label="特征字段" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="label" label="标签字段"></el-table-column>
      <el-table-column label="模型算法">
        <template #default="scope">{{ scope.row.machineLearningAlgorithm }}</template>
      </el-table-column>
      <el-table-column prop="arguments" label="参数值" :show-overflow-tooltip="true" >
        <template #default="scope">
          <div v-for="(item,index) in scope.row.trainParams" :key="index">{{item}}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
<!--            <el-button type="text" @click="handleUsePipeline(scope.row.id)">使用</el-button>-->
            <el-button type="text" class="red" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
                     :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
    </div>
  </div>

  <el-dialog
      v-model="usePipelineVisible"
      title="流水线使用"
      width="30%"
      :before-close="handleClose"
  >
    <el-form :model="useForm" width="300px">
      <el-form-item label="选择文件" >
        <el-select v-model="useForm.file" :label-width="formLabelWidth" placeholder="请选择您要使用的文件">
          <el-option
              v-for="item in fileList.valueOf()"
              :key="item.id"
              :label="item.fileName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
          <span class="dialog-footer">
            <el-button @click="usePipelineVisible = false">取消</el-button>
            <el-button type="primary" @click="goPipeline(useForm.file)" style="margin-left: 10px">使用流水线</el-button>
          </span>
    </template>
  </el-dialog>

  <el-dialog v-model="downloadVisible" title="下载预测结果" width="30%">
    <el-form width="300px">
      <el-form-item label="文件名称" required>
        <el-input v-model="fileName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
          <span class="dialog-footer">
            <el-button @click="downloadVisible = false">取消</el-button>
            <el-button type="primary" @click="download" style="margin-left: 10px"> 下载 </el-button>
          </span>
    </template>
  </el-dialog>

</div>
</template>

<script>
import {reactive, ref} from "vue";
import {deletePipeline, getAllPipeline, usePipeline} from "../../api/pipeline";
import {ElMessage, ElMessageBox} from "element-plus";
import {GetAllFile} from "../../api/file";
import {downloadFile} from "../../api/utils";

export default {
  name: "MLPipeline",
  setup(){
    const query = reactive({
      file: "",
      name: "",
      pageIndex: 1,
      pageSize: 10,
    });
    const pageTotal = ref(0);
    const tableData = ref();
    let usePipelineVisible = ref(false)
    let useForm = reactive({
      file: "",
    })
    const formLabelWidth='120px'
    const fileList = ref()
    let usePipelineId = ref()
    let fileName = ref('')
    let downloadUri = ref()
    let downloadVisible = ref(false)

    const getPage = () => {
      const userId = localStorage.getItem("ms_userId");
      GetAllFile(userId).then(res=>{
        fileList.value=res.result;
      })
      getAllPipeline({userId}).then(res =>{
        tableData.value = res.result
        pageTotal.value = tableData.value.length
      })
    }
    getPage()

    const handleUsePipeline = (pid) => {
      usePipelineVisible.value = true
      usePipelineId.value = pid
    }
    const goPipeline = (fileId) => {
      if (fileId === ""){
        alert("请填写信息！")
        return
      }
      usePipelineVisible.value = false
      let data ={
        pipelineId: usePipelineId.value,
        fileId: fileId,
        modelName: `流水线${usePipelineId.value}的模型`
      }
      ElMessageBox( {
        title: "确定要使用流水线吗？",
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '预测中...'
            usePipeline(data).then(res=>{
              instance.confirmButtonLoading = false
              console.log("predic_res: ",res);
              if (res.msg === '成功')
              {
                handleDownload(res.result.predictedFileDownloadingUri)
                done()
              }
              else
              {
                ElMessage.error("预测失败!失败码:"+res.msg);
                done()
              }
            }).catch(err=>{
              console.log(err)
            });
          } else {
            done()
          }
        },
      })
    }

    const handleDownload=(url)=>{
      downloadVisible.value =true
      downloadUri.value = url
    }
    const download = () =>{
      const payload={
        fileUri: downloadUri.value
      }
      downloadFile(payload).then(data=>{
        downloadVisible.value = false
        let file = new Blob(["\ufeff" + data], { type: 'text/csv'});
        if (window.navigator.msSaveOrOpenBlob)
            // IE10+
          window.navigator.msSaveOrOpenBlob(file, fileName.value);
        else {
          // Others
          let a = document.createElement("a"),
              url = URL.createObjectURL(file);
          a.href = url;
          a.download = fileName.value;
          document.body.appendChild(a);
          a.click();
          setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
          }, 0);
        }
      })
    }
    const handleDelete = (pid) => {
      ElMessageBox.confirm("确定要删除此流水线吗？", "提示", {
        type: "warning",
      }).then(()=>{
            deletePipeline({pid}).then(res=>{
              if(res.msg === '成功'){
                ElMessage.success("删除成功");
              }
              else{
                ElMessage.error("删除失败");
              }
            })
          })
    }

    return{
      query,
      pageTotal,
      tableData,
      usePipelineVisible,
      useForm,
      formLabelWidth,
      fileList,
      usePipelineId,
      fileName,
      downloadVisible,
      handleDownload,
      download,
      getPage,
      handleUsePipeline,
      handleDelete,
      goPipeline,
    }
  }
}
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.green {
  color: rgb(32, 220, 88)
}
.yellow{
  color:yellowgreen;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>